package com.tledu.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * post 表单json格式数据提交
 */
public class HttpClient04 {
    public static void main(String[] args) throws IOException {
        // 这是我写的一个接口，这个接口请求方式post ，传参方式 json
        String url = "http://59.111.104.209:13000/json";
        // 1. 创建httpclient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建post请求
        HttpPost httpPost = new HttpPost(url);


        // 3. 封装参数{"name":"json格式数据"}
        String jsonString = "{\"name\":\"json格式数据\"}";
        // 4. 封装请求体
        StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
        // 5. 设置请求体
        httpPost.setEntity(stringEntity);
        // 需要指定请求头，设置Content-Type,指定成json格式
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");


        // 6. 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 7. 判断状态码
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            httpPost.abort();
            System.out.println("请求失败,当前的状态码为:" + status);
        } else {
            HttpEntity entity = response.getEntity();
            // 8. 获取请求结果
            System.out.println(EntityUtils.toString(entity));
            // 9. 关闭响应
            EntityUtils.consume(entity);
            response.close();
        }
    }
}
